import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios' // 导入axios 请求服务器
import IndexPage from '../views/IndexPage.vue' //主页模块
import Home from '../views/Home.vue' //主页
import Login from '../views/Login.vue' //登陆页
import Myself from '../views/personal/Myself.vue' //个人中心/主页
import MyInfo from '../views/personal/MyInfo.vue' //个人中心/主页
import AddHouse from '../views/house/AddHouse.vue' //个人中心/发布房源页
import MyHouseList from '../views/personal/MyHouseList.vue' //个人中心/我的仓库
import MyHouseInfo from '../views/personal/MyHouseInfo.vue' //个人中心/详情页
import HouseInfo from '../views/house/HouseInfo.vue' //详情页
import SelectNewHouse from '../views/house/SelectNewHouse.vue' //房源筛选页

Vue.use(VueRouter)

const routes = [{ //主页
    path: '/',
    redirect: '/home'
  },
  { // 登陆页面
    path: '/login',
    component: Login
  },
  // 主页
  {
    path: '/home',
    component: Home,
    redirect: '/indexPage',
    children: [{
      path: '/indexPage',
      component: IndexPage
    }]
  },
  { //房源详情页
    path: '/houseInfo',
    component: HouseInfo
  },
  { //新房源筛选页
    path: '/selectNewHouse',
    component: SelectNewHouse
  },
  //个人中心页
  {
    path: '/myself',
    component: Myself,
    redirect: '/myInfo',
    children: [{
        //个人中心主页
        path: '/myInfo',
        component: MyInfo
      },
      { //个人中心/发布房源
        path: '/addHouse',
        component: AddHouse
      },
      { //个人中心/我的仓库
        path: '/myHouseList',
        component: MyHouseList
      },
      //个人中心的详情页
      {
        path: '/myHouseInfo',
        component: MyHouseInfo
      }
    ]
  }
]
const router = new VueRouter({
  routes
})

// 挂载路由导航守卫 登陆拦截
router.beforeEach(async (to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //     next()  放行    next('/login')  强制跳转
  // 如果访问登陆和主页就放行
  // console.log(to.path);
  if (to.path === '/login' || to.path === '/indexPage' || to.path === '/selectNewHouse' || to.path === '/houseInfo') return next()
  // 获取user
  //后端登陆状态验证

  const {
    data: user
  } = await axios.post('UserController/getUser.action');
  console.log(user + 'user');
  
   //获取客户端存储的用户
  if (!user) return next('/login') // 未登陆到登陆页面
  next() // 登陆放行
})


export default router
